<?php
    /**
     * @name 核心类库
     * @copyright tcsos inc
     * @version cooperation v1.0
     */

    class cooperation{
        private static $name = '';         //框架名称
        private static $version = '';      //版本号
        private static $config = array();       //配置文件
        private static $root = '';         //网站目录
        private static $mysql = array();   //数据库对象
        private static $area;              //地区对象
        private static $file;              //文件对象
        private static $smtp;              //邮件对象
        private static $log;                //日志对象
        private static $webim;              //webim对象
        private static $invite;             //邀请对象
        private static $sms;                //短信接口对象
        private static $video;              //视频对象
        private static $memcache;           //memcache对象
        private static $mongodb;            //mongodb对象
        private static $crypt;              //加密解密对象
		private static $qrcode;				//二维码对象
		private static $onecode;			//一维码对象
        private static $_init = false;      //是否进行了初始化
        private static $_gzip;              //是否开启GZIP
        private static $_obend = false;     //是否执行ob_end
        public static $is_view = '';        //模块

        /**
         * 构造函数
         *
         */
        public function __construct(){
            if(self::$_init) {
                return;
            }

            //ROOT目录
            self::$root = substr(dirname(__FILE__), 0, -11);

            //初始化配置
            $this->_init_config();

            //初始化环境
            $this->_init_env();

            //初始化输入
            $this->_init_input();

            //初始化输出
            $this->_init_output();

            //初始化日志
            $this->_init_log();

            self::$_init = true;
        }

        /**
         * 析构函数
         *
         */
        public function __destruct(){

            //清除MYSQL，CLOSE
            if(self::$mysql && !empty(self::$mysql)) {
                foreach(self::$mysql as $k => $v) {
                    $v->__destruct();
                }
            }

            if(!self::$_gzip || self::$_obend){
                return;
            }

            if(!self::$is_view) {
                return;
            }

            header('Cache-Control: post-check=0, pre-check=0');
            header('Pragma: ');
            ob_end_flush();

            /*$content = ob_get_contents();
            ob_end_clean();
            ob_start('ob_gzhandler');
            echo $content;*/

            self::$_obend = true;
            exit;
        }

        /**
         * 初始化环境
         *
         */
        private function _init_env(){
            //发生致命性错误
            error_reporting(E_ERROR);

            //框架名
            self::$name = 'Tcsos Cooperation';

            //版本号
            self::$version = '1.0 beta';

            //设置时间区
            $this->set_timezone();

            //runtime地址
            $common_path = $common_path = $this->get_libpath('common');

            if(self::$config['runtime']['cache']) {
                $common_path = $this->get_datapath('cache/runtime/common');
                if(!is_file($common_path)) {
                    $common = file_get_contents($this->get_libpath('common'));
                    $common = $this->strip_whitespace($common);
                    $this->_file()->write_content($common, $common_path);
                }
            }

            require_once $common_path;
        }

        /**
         * 初始化配置
         *
         */
        public function _init_config() {
            $_libconfig = array();
            require_once $this->_root() . '/source/config.php';
            self::$config = $_libconfig;
        }

        /**
         *
         * 初始化输入配置
         */
        private function _init_input() {
            if(isset($_GET['GLOBALS']) || isset($_POST['GLOBALS']) || isset($_REQUEST['GLOBALS']) || $_FILES['GLOBALS'] || $_COOKIE['GLOBALS']) {
                exit('class core GLOBALS exit.');
            }

            //如果没有开启单引号转义，进行手动处理
            if(!function_exists('get_magic_quotes_gpc') || !get_magic_quotes_gpc()) {
                $_GET = taddslashes($_GET);
                $_POST = taddslashes($_POST);
                $_REQUEST = taddslashes($_REQUEST);
                $_FILES = taddslashes($_FILES);
            }

            //POST/GET的处理
            if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST)) {
                $_GET = array_merge($_GET, $_POST);
            }


            unset($_POST);
        }

        /**
         *
         * 初始化输出配置
         */
        private function _init_output() {
            //开启SESSION
            session_start();                                                            

            //启用编码  . self::$config['sys']['charset']  造成油料接口数据获取失败 @author leiqianyong 2020-6-28 14:56 PM 
            //@header('charset=utf-8');
            @header("Content-type: text/html; charset=utf-8");
            @header('X-Powered-By:Tcsos Cooperation V1.0');

            //是否开启gzip
            $gzip_enable = request('gzip',false,true,false,self::$config['sys']['gzip']);

            //GZIP开启条件，gzip开启，配置gzip开启
            if(!function_exists('ob_gzhandler') || $gzip_enable != 1) {
                self::$_gzip = false;
                return;
            }

            //ob_start('ob_gzhandler');
            ob_start('ob_gzip');
            self::$_gzip = true;
        }

        /**
         * 初始化日志对象
         *
         * @return void
         */
        private function _init_log() {
            require_once $this->get_libpath('log');
            self::$log = new log(self::$root . self::$config['log']['path'], self::$config['log']['level']);
        }
        /**
         * 获取核心路径
         *
         * @param mixed $file   文件名
         * @return string
         */
        public function get_libpath($file) {
            if(empty($file)) {
                return false;
            }

            return realpath(self::$root . "/source/lib/{$file}.php");
        }

        /**
         * 获取缓存文件路径
         *
         * @param string $file  文件路径
         * @return string
         */
        public function get_datapath($file) {
            if(empty($file)) {
                return false;
            }

            return self::$root . "/data/{$file}.php";
        }

        /**
         * 获取视图文件
         *
         * @param string $file  视图文件路径
         * @return string
         */
        public function get_viewpath($file) {
            if(empty($file)) {
                return false;
            }

            return realpath(self::$root . "/view/{$file}.php");
        }

        /**
         * 获取handle文件
         *
         * @param string $file  handle文件路径
         */
        public function get_handlepath($file) {
            if(empty($file)) {
                return false;
            }

            return realpath(self::$root . "/source/handle/{$file}.php");
        }

        /**
         * 获取对象文件
         *
         * @param string $file  对象文件路径
         * @return string
         */
        public function get_objectpath($file) {
            if(empty($file)) {
                return false;
            }

            return realpath(self::$root . "/source/object/{$file}.php");
        }

        /**
         * 设置时区
         * @return void
         */
        private function set_timezone() {
            if(!function_exists('date_default_timezone_set')) {
                return false;
            }
            date_default_timezone_set('Asia/Chongqing');
        }



        //====================================================================================
        // 用于外部调用核心对象的
        //====================================================================================

        /**
         * 获取框架名
         * @return string
         */
        public function _name(){
            return self::$name;
        }

        /**
         * 获取版本
         * @return string
         */
        public function _version(){
            return self::$version;
        }

        /**
         * 获取配置信息
         * @return array
         */
        public function &_config(){
            return self::$config;
        }

        /**
         * 获取网站根目录
         * @return string
         */
        public function _root(){
            return self::$root;
        }

        /**
         * 获取地区对象
         * @return area对象
         */
        public function _area(){
            if(is_object(self::$area)) {
                return self::$area;
            }
            //初始化地区
            require_once $this->get_libpath('class/area');
            self::$area = new area(self::$root.'/'.self::$config['area']['xmp_path'] , self::$config['area']['api_path']);
            return self::$area;
        }

        /**
         * 获取短信接口
         * @return sms
         */
        public function _sms(){
            if(is_object(self::$sms)) {
                return self::$sms;
            }
            require_once $this->get_libpath('class/sms');
            self::$sms = new sms(self::$config['sms']);
            return self::$sms;
        }

        /**
         * 获取数据库对象
         *
         * @param mixed $k  数据库键
         * @return mysql对象
         */
        public function _mysql($k=0) {
            if(is_object(self::$mysql[$k])) {
                return self::$mysql[$k];
            }

            require_once $this->get_libpath('class/mysql');
            self::$mysql[$k] = new mysql(self::$config['db'][$k], self::$log);
            return self::$mysql[$k];
        }

        /**
         * 获取文件对象
         * @return file对象
         */
        public function _file(){
            if(is_object(self::$file)) {
                return self::$file;
            }

            //初始化file
            require_once $this->get_libpath('class/file');
            self::$file = new file();
            return self::$file;
        }

        /**
         * 获取smtp对象
         * @return smtp对象
         */
        public function _smtp(){
            if(is_object(self::$smtp)) {
                return self::$smtp;
            }
            //初始化smtp
            require_once $this->get_libpath('class/smtp');
            self::$smtp = new smtp(self::$config['smtp']);
            return self::$smtp;
        }

        /**
         * 获取video对象
         *
         * @author zhouqi 2012-1-5 AM 10:14:56
         * @return video对象
         */
        public function _video() {
            if(is_object(self::$video)) {
                return self::$video;
            }

            //初始化video
            require_once $this->get_libpath('class/video');
            self::$video = new video();
            return self::$video;
        }

        /**
         * 获取memcache对象
         *
         * @author zhouqi 2012-10-30 PM 03:32:00
         * @return memcache对象
         */
        public function _memcache() {
            if(is_object(self::$memcache)) {
                return self::$memcache;
            }

            //初始化video
            require_once $this->get_libpath('class/cache_memcache');
            self::$memcache = new cache_memcache(self::$config['memcache']);
            return self::$memcache;
        }

        /**
         * 获取mongodb对象
         *
         * @author zhouqi 2012-10-30 PM 04:20:22
         * @return mongodb对象
         */
        public function _mongodb() {
            if(is_object(self::$mongodb)) {
                return self::$mongodb;
            }

            //初始化video
            require_once $this->get_libpath('class/cache_mongodb');
            self::$mongodb = new cache_mongodb(self::$config['mongodb']);
            return self::$mongodb;
        }

		/**
         * 获取二维码对象
         *
         * @author zhouqi 2012-11-20 PM 02:39:12
         * @return invite
         */
		public function _qrcode() {
			if(is_object(self::$qrcode)) {
                return self::$qrcode;
            }

            require_once $this->get_libpath('class/qrcode');
            self::$qrcode = new tdcode();
            return self::$qrcode;
		}


		/**
         * 获取一维码对象
         *
         * @author zhufu 2014-05-21
         * @return object
         */
		public function _onecode() {
			if(is_object(self::$onecode)) {
                return self::$onecode;
            }

            require_once $this->get_libpath('class/onecode');
            self::$onecode = new onecode();
            return self::$onecode;
		}


        /**
         * 获取invite对象
         *
         * @author zhouqi 2012-7-4 AM 09:59:14
         * @return invite
         */
        public function _invite() {
            if(is_object(self::$invite)) {
                return self::$invite;
            }

            //初始化video
            require_once $this->get_libpath('class/invite');
            self::$invite = new invite();
            return self::$invite;
        }

        /**
         * 获取webim接口对象
         * @return webim对象
         */
        protected function _webim(){

            if(is_object(self::$webim)) {
                return self::$webim;
            }

            require_once $this->get_libpath('class/webim');
            self::$webim = new webim(
            self::$config['webim']['socket']['host'],
            self::$config['webim']['socket']['port'],
            self::$config['webim']['webapp']['host'],
            self::$config['webim']['webapp']['port'],
            self::$config['webim']['webapp']['sid_url']
            );
            return self::$webim;
        }

        /**
         * 去除代码中的空白和注释
         *
         * @author zhouqi 2012-8-16 AM 11:43:25
         * @param string $content   内容
         */
        public function strip_whitespace($content) {
            $stripStr = '';
            //分析php源码
            $tokens = token_get_all($content);
            $last_space = false;
            for ($i = 0, $j = count($tokens); $i < $j; $i++) {
                if (is_string($tokens[$i])) {
                    $last_space = false;
                    $stripStr .= $tokens[$i];
                    continue;
                }

                switch ($tokens[$i][0]) {
                    //过滤各种PHP注释
                    case T_COMMENT:
                    case T_DOC_COMMENT:
                        break;
                        //过滤空格
                    case T_WHITESPACE:
                        if (!$last_space) {
                            $stripStr .= ' ';
                            $last_space = true;
                        }
                        break;
                    case T_START_HEREDOC:
                        $stripStr .= "<<<TCSOS\n";
                        break;
                    case T_END_HEREDOC:
                        $stripStr .= "TCSOS;\n";
                        for($k = $i+1; $k < $j; $k++) {
                            if(is_string($tokens[$k]) && $tokens[$k] == ';') {
                                $i = $k;
                                break;
                            }

                            if($tokens[$k][0] == T_CLOSE_TAG) {
                                break;
                            }
                        }
                        break;
                    default:
                        $last_space = false;
                        $stripStr .= $tokens[$i][1];
                }
            }
            return $stripStr;
        }

    }

    //初始化框架
    $_cooper = new cooperation();
?>
